package org.batatasframework.chart.data;

import java.util.Arrays;

import org.batatasframework.chart.columns.ChartColumn;
import org.batatasframework.chart.graphics.ChartGraphic;

public class ChartTableResolver extends AbstractChartResolver{
	
	private final StringBuilder html = new StringBuilder();
	private String graphics = "[]";
	
	public ChartTableResolver(ChartData data){
		super(data);
	}
	
	protected void internalInitialize(){
		if(!definition.getGraphics().isEmpty()){
			String graphicArray = "";
			for(ChartGraphic graphic : definition.getGraphics()){
				graphicArray += "," + graphic.resolve(axis);
			}
			
			this.graphics = "[" + graphicArray.substring(1) + "]";
		}

		//  ---  下面开始处理表格数据
		
		String[] heads = new String[headRowCount];
		Arrays.fill(heads, "");
		
		axis.resolveHead(heads, 0);
		for(ChartColumn column : definition){
			column.resolveHead(heads, 0);
		}
		
		html.append("<table class='c_t_i'><thead>");
		boolean first = true;
		for(String head : heads){
			html.append("<tr>");
			if(first){
				html.append("<th");
				if(headRowCount > 1)html.append(" rowspan='").append(headRowCount).append("'");
				html.append(">序号</th>");
				
				first = false;
			}
			html.append(head).append("</tr>");
		}
		html.append("</thead><tr><th style='text-align:right;' colspan='").append(axis.size() + 1).append("'>合计：</th>");
		for(Object obj : data.summary){
			html.append("<th>").append(obj).append("</th>");
		}
		html.append("</tr>");
		
		//  ----   下面是数据的内容
		
		int ordinal = 1,
			pageIndex = 1, 
			pageSize = definition.getPageSize(), 
			fullSize = pageSize * pageIndex;
		
		html.append("<tbody id='c_t_d'>");
		for(Object[] objs : data.data){
			html.append("<tr");
			if(ordinal > fullSize){
				pageIndex++;
				fullSize = pageSize * pageIndex;
				html.append(" style='display:none;' class='p_010_h ");
			}else{
				html.append(" class='");
			}
			html.append("p_010_").append(pageIndex).append("'><td>").append(ordinal++).append("</td>");
			
			for(Object obj : objs){
				html.append("<td>").append(obj).append("</td>");
			}
			html.append("</tr>");
		}
		html.append("</tbody></table>");
		if(pageIndex > 1){
			//出现了分页的情况
			html.append("<div class='c_p_f'>");
			html.append("共：").append(data.data.length);
			html.append("</div>");
		}
		
	}

	@Override
	public String toString() {
		return html.toString();
	}
	
	public String getGraphics() {
		return graphics;
	}
}
